package com.jkt.rms.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.jkt.rms.business.Authorities;
import com.jkt.rms.businessservice.RoleBusinessService;
import com.jkt.rms.businessservice.UserBusinessService;
import com.jkt.rms.commons.utils.ExceptionFactory; 
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.commons.utils.ServiceLocator;
import com.jkt.rms.constants.IConstants;

import com.jkt.rms.vo.SystemRoleVO;
import com.jkt.rms.vo.UsersVO;

public class UserMaintenanceController extends AbstractMultiActionController {

	private static final Logger LOG = Logger.getLogger(UserMaintenanceController.class);
	private RoleBusinessService roleBusinessService = ServiceLocator.getServiceLocator().locate("roleBusinessService");
	private UserBusinessService userBusinessService = ServiceLocator.getServiceLocator().locate("userBusinessService");
	
	public ModelAndView loadUser(HttpServletRequest request,HttpServletResponse response,UsersVO user) {
		LOG.debug("[UserMaintenanceController loadUser Start]");
		user.setListRole(getUserRole());
		return new ModelAndView("adduser","user",user);
	}
	
	public ModelAndView addUser(HttpServletRequest request,HttpServletResponse response,UsersVO user) throws RMSException  {
		LOG.debug("UserMaintenanceController addUser Start");
		user.setValidationType(IConstants.VALIDATE_ADD);
		validate(user);
		user.setListRole(getUserRole());
		if (errors != null && errors.getAllErrors() != null
				&& errors.getAllErrors().size() > 0) {
			return new ModelAndView("adduser", "user", user).addObject("errors", errors);
		} else {
			try {
				if(userBusinessService.saveUsers(user)){
					user.setMessage("user.success.message");
					resetFields(user);
				}else{
					if(userBusinessService.getMessage().equals(IConstants.EXISTS)){
						errors.rejectValue("email", "error.allreadyexists", new String[]{"Email"}, null);
					}else {
						errors.rejectValue("username", "error.allreadyexists", new String[]{"UserName"}, null);
					}
					return new ModelAndView("adduser", "user", user).addObject("errors", errors);
				}
			} catch (RMSException e) {
				LOG.debug("Exception in addUser",e.getCause());
				user.setMessage(e.getBusinessCode());
			} catch (Exception ex) {
				ExceptionFactory.createRMSException(LOG, ex.getCause(), IConstants.FAILURE_MESSAGE);
				//user.setMessage(IConstants.FAILURE_MESSAGE);
			}
		}
		
		return new ModelAndView("adduser","user",user);
		
	}
	
	public ModelAndView search(HttpServletRequest request,HttpServletResponse response,UsersVO user) throws RMSException {
		LOG.info("search user");
		UsersVO userVO = new UsersVO();
		userVO.setSrchFirstName(user.getSrchFirstName());
		userVO.setListRole(getUserRole());
		userVO.setSearchMethod("search");
		user.setValidationType(IConstants.VALIDATE_SEARCH);
		validate(user);
		if (errors != null && errors.getAllErrors() != null
				&& errors.getAllErrors().size() > 0) {
			return new ModelAndView("adduser", "user", user).addObject("errors", errors);
		} else {
			
			List<UsersVO> userList = userBusinessService.searchUser(user);
			if(userList == null || userList.size() == 0){
				userVO.setMessage("no.record.found");
			}
			
			return new ModelAndView("adduser","user", userVO)
			.addObject("userSearch", userList);
			
		}
		
	}
	
	public ModelAndView searchAll(HttpServletRequest request,HttpServletResponse response) throws RMSException {
		LOG.info("Search All user");
		UsersVO user = new UsersVO();
		user.setListRole(getUserRole());
		List<UsersVO> userList = userBusinessService.findAllUsers();
		if(userList == null || userList.size() == 0){
			user.setMessage("no.record.found");
		}
		user.setSearchMethod("searchAll");
		return new ModelAndView("adduser","user", user).addObject("userSearch", userList);
	}
	
	public ModelAndView editUI(HttpServletRequest request,HttpServletResponse response,UsersVO user) {
		try {
			UsersVO searchUserVO = new UsersVO();
			searchUserVO.setSrchFirstName(user.getSrchFirstName());
			searchUserVO.setSrchLastName(user.getSrchLastName());
			searchUserVO.setSrchRoleName(user.getSrchRoleName());
			searchUserVO.setSrchUserName(user.getSrchUserName());
			searchUserVO.setSearchMethod(user.getSearchMethod());
			
			user = userBusinessService.getUserDataByName(user.getUsername());
			List<Authorities> listAuthor =  user.getListUserRoles();
			for (Authorities authorities : listAuthor) {
				if(!(authorities.getAuthority().equals(IConstants.ROLE_NAME))){
					user.setRoleName(authorities.getAuthority());
				}
			}
			
			populateSearchCriteria(user,searchUserVO);
		} catch (RMSException e) {
			ExceptionFactory.createRMSException(LOG, e.getCause(),e.getMessage());
		}
		return new ModelAndView("updateuser","user",user);
	}
	
	public ModelAndView update(HttpServletRequest request,HttpServletResponse response,UsersVO user) { 
		LOG.debug("UserMaintenanceController Update Start");
		user.setValidationType(IConstants.VALIDATE_UPDATE);
		UsersVO searchUserVO = new UsersVO();
		searchUserVO.setSrchFirstName(user.getSrchFirstName1());
		searchUserVO.setSrchLastName(user.getSrchLastName1());
		searchUserVO.setSrchRoleName(user.getSrchRoleName1());
		searchUserVO.setSrchUserName(user.getSrchUserName1());
		searchUserVO.setSearchMethod(user.getSearchMethod1());
		validate(user);
		
		if (errors != null && errors.getAllErrors() != null
				&& errors.getAllErrors().size() > 0) {
			populateSearchCriteria(user,searchUserVO);
			return new ModelAndView("updateuser", "user", user).addObject("errors", errors);
		} else {
			try {
				if(userBusinessService.updateUserData(user)){
					user.setMessage("user.success.update.message");
				}
			}
			 catch (Exception ex) {
				ExceptionFactory.createRMSException(LOG, ex.getCause(), IConstants.FAILURE_MESSAGE);
			}
		}
		populateSearchCriteria(user, searchUserVO);
		return new ModelAndView("updateuser","user",user);
		
	}
	
	
	
	private List<SystemRoleVO> getUserRole() {
		List<SystemRoleVO> sysRoleVOList = null;
		try {
			sysRoleVOList =   roleBusinessService.findAllRoles();
		} catch (RMSException e) {
			LOG.debug("[Exception in loadUser]",e.getCause());
		}
		return sysRoleVOList;
	}
	private void resetFields(UsersVO user ) {
		user.setFirstName("");
		user.setLastName("");
		user.setRoleName("0");
		user.setUsername("");
		user.setEmail("");
	}
	
	private void populateSearchCriteria(UsersVO user,UsersVO searchUserVO) {
		user.setSrchFirstName(searchUserVO.getSrchFirstName());
		user.setSrchLastName(searchUserVO.getSrchLastName());
		user.setSrchRoleName(searchUserVO.getSrchRoleName());
		user.setSrchUserName(searchUserVO.getSrchUserName());
		user.setSearchMethod(searchUserVO.getSearchMethod());
		user.setListRole(getUserRole());
	}
	
	
}
